package com.googletran;



import java.util.ArrayList;

import android.app.Activity;
import android.app.ProgressDialog;
import android.content.Intent;
import android.content.SharedPreferences;
import android.database.Cursor;
import android.graphics.Color;
import android.net.Uri;
import android.os.Bundle;
import android.preference.PreferenceManager;
import android.view.View;
import android.webkit.WebView;
import android.webkit.WebViewClient;
import android.widget.ImageButton;
import android.widget.Toast;

public class SDictContentView extends Activity{
	//////////Bien TAG/////////
	static final private String CONTENT_TAG = "[Smart Dictionary - Content]";
	
	
	///////Bien Dieu Khien//////////
	private WebView wvContent = null;
    private ImageButton btnGoBack = null;
    private ImageButton btnGoNext = null;
    private ImageButton btnShowHistory = null;
    private ImageButton btnAddFavourite = null;
    
    
    //////Bien lay du lieu da nap khi goi Intent////////
    private String mCurrentWord;
    private String mSelectedDB;
    private String mContentStyle;
    private int mCurrentWordId;
    private int mCurrentHistoryIndex = -1;
    
    private ArrayList<String> mWordHistory = null; //Mang cac tu da tra
    
    
    ////////Bien luu tru tam///////////
    private SharedPreferences prefs;
    
    
    
    //////Tao Dialog wait////
    private ProgressDialog pd = null;
    
    /////Khai bao bien Dinh dang Web////
    private static final String MIMETYPE = "text/html";
    private static final String ENCODING = "UTF-8";
    
    @Override
    public void onCreate(Bundle savedInstanceState) {
	    super.onCreate(savedInstanceState);
	    setContentView(R.layout.webview);
	    
	    
	    Intent i = this.getIntent();
	    int wordId = i.getIntExtra("id", -1);
	    mCurrentWord = i.getStringExtra("word");
	    mSelectedDB = i.getStringExtra("db");
	    mContentStyle = i.getStringExtra("style");
	    
	    prefs = PreferenceManager.getDefaultSharedPreferences(getApplicationContext());
	    
	    wvContent = (WebView) findViewById(R.id.wvContent);
    	initWebview();
    	String content = getContentById(wordId);
    	showContent(content);
    	
    	
    	btnGoBack = (ImageButton) findViewById(R.id.btnGoBack);
    	btnGoBack.setOnClickListener(new View.OnClickListener() {
					
			public void onClick(View v) {				
				goBack();
			}
		});
    	
    	btnGoNext = (ImageButton) findViewById(R.id.btnGoNext);
    	btnGoNext.setOnClickListener(new View.OnClickListener() {
			
			public void onClick(View v) {				
				menuList();
			}
		});
    	
    	btnAddFavourite = (ImageButton) findViewById(R.id.btnAddFavourite);
    	btnAddFavourite.setOnClickListener(new View.OnClickListener() {
						public void onClick(View v) {
				// TODO Auto-generated method stub
				Toast toast = Toast.makeText(SDictContentView.this, R.string.luufavourite, Toast.LENGTH_SHORT);
				toast.show();
			}
		});
    	
    }
    ////////Xem tu truoc do////////////
    public void goBack()
    {
    	Intent i = this.getIntent();
    	int wordId = i.getIntExtra("id", -1);
    	String content = getContentById(wordId -1);
    	showContent(content);
    	
    }
    
    //////////Xem tu tiep theo/////
    public void goNext()
    {
    	Intent i = this.getIntent();
    	int wordId = i.getIntExtra("id", -1);
    	String content = getContentById(wordId +1);
    	showContent(content);
    	
    }
    
    public void menuList()
	{		
		Intent i = new Intent();
		i.putExtra("word", mCurrentWord);
		setResult(RESULT_OK,i);
		finish();
	}
    
    ////////////Show du lieu vao Web view////
    public void showContent(String content)
    {
    	if (content != null)
    	{
    		pd = ProgressDialog.show(this, "Working..", "Loading content", true,false);    		
    		/////// Chua luu tru tu` vao history///
    		//saveHistory();
            wvContent.loadDataWithBaseURL (null, content, MIMETYPE, ENCODING,"about:blank");
    	}
    }
    
    
    
    /////////////Ham khoi tao WebView/////////////
    public void initWebview()
    {
    	setContentView(R.layout.webview);
    	wvContent = (WebView) findViewById(R.id.wvContent);
	 	wvContent.setBackgroundColor(Color.argb(255, 0, 0, 0));
	 	
        wvContent.setWebViewClient(new WebViewClient() 
        {
        	public void onPageFinished(WebView view, String url)
        	{
        		if (pd != null)
        		{
        			pd.dismiss();
        			pd = null;
        		}
        	}
        	/*
        	@Override
        	public boolean shouldOverrideUrlLoading(WebView view, String url)
        	{
        		Log.i(CONTENT_TAG,"WebView link clicked; url = " + url);
        		try
        		{
            		String arrUrlPart[] = url.split("://");
            		
            		if (arrUrlPart[0].equals("entry"))
            		{
            			String content = getContentByWord(arrUrlPart[1]);
            			showContent(content);
            		}
            		else if (arrUrlPart[0].equals("http"))
            		{
            	         try {                             
            	        	 startActivity(new Intent(Intent.ACTION_VIEW, Uri.parse(url)));             	        	 
            	         } catch (Exception ex) {
                             // TODO Auto-generated catch block
                             ex.printStackTrace();
            	         }             			
            		}
        		}
        		catch (Exception ex)
        		{
        			ex.printStackTrace();
        		}
        		return true;
        	}*/
        });
    }
    
    /////////////////Tim tu theo ID///////////////
    public String getContentById(int id)
    {
		Uri uri = Uri.parse("content://com.googletran.DBContentProvider/dict/" + mSelectedDB + "/contentId/" + id);

		Cursor result = managedQuery(uri,null,null,null,null);
		
    	String content;
        if (result != null)
        {
        	result.moveToFirst();
        	content = com.googletran.Utility.decodeContent(result.getString(result.getColumnIndex("content")));
        	mCurrentWordId = result.getInt(result.getColumnIndex("id"));
        	mCurrentWord = result.getString(result.getColumnIndex("word"));
        }
        else // Word not found
        {
        	content = getString(R.string.errorWordNotFound);
        	mCurrentWordId = -1;
        	mCurrentWord = "";
        }
        content = formatContent(content);
                
        return content;
    }

    
    ////////////////////////Tuy chinh font chu//////////
    public String formatContent(String content)
    {
		StringBuilder htmlData = new StringBuilder();
		htmlData.append("<html><meta http-equiv=\"Content-Type\" content=\"text/html; charset=UTF-8\"/>\n");
		if (mContentStyle != null && !mContentStyle.equals(""))
		{
			htmlData.append("<head><style type=\"text/css\">"+mContentStyle+"</style></head>\n");
		}
		htmlData.append("<body><font face=\"Times New Roman\">");

		htmlData.append(content);
		
		htmlData.append("</font></body></html>");
		
		return htmlData.toString();
    }
}
